package models

import (
	"time"
)

type Project struct {
	Model
	Name        string `json:"name"`        // 项目名称
	Description string `json:"description"` // 项目描述
	Icon        string `json:"icon"`        // 项目logo
	Uid         int    `json:"uid"`         // 创建人ID
	Pin         int    `json:"pin"`         // 收藏时间
}

type ProjectDashboard struct {
	Project
	CiCount CiCount `json:"ci_count"`
}

type CiCount struct {
	Total    int `json:"total"`
	NotBuild int `json:"not_build"`
	Success  int `json:"success"`
	Failure  int `json:"failure"`
	Running  int `json:"running"`
	Other    int `json:"other"`
}

func CreateProject(p Project) error {
	return db.Create(&p).Error
}

func DeleteProject(id int) error {
	return db.Model(&Project{}).
		Where("id = ?", id).
		Update("deleted_at", time.Now().Unix()).
		Error
}

func ProjectIDExist(id int) bool {
	project := Project{Model: Model{ID: id}}
	count := db.Where("deleted_at = 0").First(&project).RowsAffected
	if count == 0 {
		return false
	}
	return true
}

func GetProject(p Project) Project {
	project := Project{}
	db.Where(&p).First(&project)
	return project
}

func GetProjectByID(id int) Project {
	project := Project{}
	db.Where("id = ?", id).Where("deleted_at = 0").First(&project)
	return project
}

func GetProjectByName(name string) Project {
	project := Project{}
	db.Where("name = ?", name).Where("deleted_at = 0").First(&project)
	return project
}

func GetAllProject() []*Project {
	projects := make([]*Project, 0)
	db.Where("deleted_at = 0").Order("pin desc").Order("created_at desc").Find(&projects)
	return projects
}
